﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Vega.USiteBuilder;
using SPCFMedicineInformer.Helpers;
using System.Web.Security;
using SPCFMedicineInformer.DocumentTypes;

namespace SPCFMedicineInformer.UserControls
{
    public partial class AdminLoginControl : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {            
        }

        protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
        {
            string hashedPassword = Login1.Password.ToEncryptedPassword();

            var admin = MemberHelper.GetMemberFromLoginAndEncodedPassword(Login1.UserName, hashedPassword);
            bool validLogin = admin != null && admin.Id > 0;
            if (validLogin) 
            {
                var userRoles = Roles.GetRolesForUser(Login1.UserName);

                if(userRoles.Contains(Constants.Roles.ADMINISTRATOR))
                {
                    validLogin = true;
                    MemberHelper.LoginWithFormsAuthentication(Login1.UserName,
                        Login1.Password,
                        Login1.RememberMeSet, 30, false);                
                }   
                else
                    validLogin = false;
                
            }
            e.Authenticated = validLogin;
            if (e.Authenticated)
            {                
               var redirecUrl =  NodeLocator.GetNodesOfExactType<AdminContentPage>().First().Url;
               Response.Redirect(redirecUrl);
            }            
        }
        
    }
}
